/*
 * main.cpp
 *
 *  Created on: 2019年12月11日
 *      Author: madengyun
 */
#include<iostream>
#include<queue>
#include<pthread.h>
#include<unistd.h>
#include<random>
#include<thread>
using namespace std;

pthread_key_t tlsKey1 = 0xFFFFFFFF;
pthread_key_t tlsKey2 = 0xFFFFFFFF;

void threadFun(void)
{
	cout<< "=================in thread " << this_thread::get_id() << "====================" << endl;
	cout<< "tlsKey1 = " << tlsKey1 << ", tlsKey2 = " << tlsKey2 <<endl;

	if (tlsKey1 == 0xFFFFFFFF){
		pthread_key_create(&tlsKey1, NULL);
		cout<< "after pthread_key_create, tlsKey1 = " << tlsKey1 << endl;
	}
	if (tlsKey2 == 0xFFFFFFFF){
		pthread_key_create(&tlsKey2, NULL);
		cout<< "after pthread_key_create, tlsKey2 = " << tlsKey2 << endl;
	}

	void* data1 = pthread_getspecific(tlsKey1);
	cout<< "pthread_getspecific from " << tlsKey1 << " return " << data1 <<endl;
	if (nullptr == data1){
		data1 = (void*)(new int(tlsKey1));
		pthread_setspecific(tlsKey1, data1);
	}
	data1 = pthread_getspecific(tlsKey1);
	cout<< "after pthread_setspecific, pthread_getspecific from " << tlsKey1 << " return " << data1 <<endl;

	void* data2 = pthread_getspecific(tlsKey2);
	cout<< "pthread_getspecific from " << tlsKey2 << " return " << data2 <<endl;
	if (nullptr == data2){
		data2 = (void*)(new int(tlsKey2));
		pthread_setspecific(tlsKey2, data2);
	}
	data2 = pthread_getspecific(tlsKey2);
	cout<< "after pthread_setspecific, pthread_getspecific from " << tlsKey2 << " return " << data2 <<endl;

	std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main(void)
{
	for (int i = 0; i < 4; i++){
		std::thread t1(threadFun);
		t1.detach();
	}

	std::this_thread::sleep_for(std::chrono::seconds(2));

	return 0;
}

